package enterprise.web_jpa_war.servlet;

import enterprise.web_jpa_war.entity.Customer;
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import javax.persistence.PersistenceUnit;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;


@WebServlet(name="ListCustomerOrder", urlPatterns={"/ListCustomerOrder.do"})
public class ListCustomerOrder extends HttpServlet {
    @PersistenceUnit
    private EntityManagerFactory emf;
  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        assert emf != null;                //Make sure injection went through correctly.
        EntityManager em = null;
        try {
            String cusid=request.getParameter("cusid");

            em = emf.createEntityManager();
            //"select o from Cusorder o where o.customer.id = 'cusid'"
            //query for all the persons in database
            Customer s= em.find(Customer.class, cusid);
            if(s==null){
             request.setAttribute("message","Your Customer Id not in the database. find the correct customer id");
             request.getRequestDispatcher("message.jsp").forward(request, response);
            }


            List  selorders = em.createQuery("select o from Cusorder o where o.customer.id = " + cusid).getResultList();
            
            request.setAttribute("selOrderList",selorders);
            request.setAttribute("customer", s);

            //Forward to the jsp page for rendering
           request.getRequestDispatcher("selectvieworder.jsp").forward(request, response);
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            //close the em to release any resources held up by the persistebce provider
            if(em != null) {
                em.close();
            }
        }
    } 

 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
